﻿using PMS.Core.Caching;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Services.Authentication.Externel;
using PMS.Services.Caching;
using PMS.Services.EntityServices;
using PMS.Services.EntityServices.Messages;
using PMS.Services.Utils;
using PMS.Services.Utils.Events;

namespace PMS.Services.EventHandler.Caching
{
    /// <summary>
    /// Represents a customer account changed cache event consumer
    /// </summary>
    public partial class CustomerAccountChangedCacheEventHandler
        : IEventHandler<CustomerAccountChangedEvent>
    {
        #region Fields

        private readonly ICacheKeyService _cacheKeyService;
        private readonly IStaticCacheManager _staticCacheManager;
        private readonly IExternalAuthenticationService _externalAuthService;

        #endregion

        #region Ctor

        public CustomerAccountChangedCacheEventHandler(IExternalAuthenticationService externalAuthService,
            ICacheKeyService cacheKeyService,
            IStaticCacheManager cacheManager)
        {
            _externalAuthService = externalAuthService;
            _cacheKeyService = cacheKeyService;
            _staticCacheManager = cacheManager;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Handle event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(CustomerAccountChangedEvent eventMessage)
        {
            if (eventMessage.Mode != AccountBindMode.Email)
            {
                var verifySMSCodeKey = _cacheKeyService.PrepareKey(CacheKeyConfigs.CustomerSMSVerifyCodeCacheKey, SMSTemplateNames.CustomerBindAccountTemplateMessage, eventMessage.Customer.Id);
                _staticCacheManager.Remove(verifySMSCodeKey);
            }
            else
            {
                var verifyEmailCodeKey = _cacheKeyService.PrepareKeyForDefaultCache(CacheKeyConfigs.CustomerEmailVerifyCodeCacheKey, EmailMessageTemplateNames.CustomerSendChangeEmailAccountCodeMessage, eventMessage.Customer.Id);
                _staticCacheManager.Remove(verifyEmailCodeKey);
            }

            //Remove ExternalAccount associated to the current account
            //use customer.id only
            var externalRecords = _externalAuthService.GetCustomerExternalAuthenticationRecords(eventMessage.Customer);
            if ((externalRecords?.Count ?? 0) > 0)
            {
                foreach (var externalRecord in externalRecords)
                {
                    _externalAuthService.DeleteExternalAuthenticationRecord(externalRecord);
                }
            }

        }

        #endregion
    }

}
